package com.dm.wallpaper.library.ablility.slice;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.ablility.callbacks.SplashScreenCallback;
import com.dm.wallpaper.library.ablility.configurations.SplashScreenConfiguration;
import com.dm.wallpaper.library.database.Database;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

/*
 * Copyright (C) 2021 The Chinese Software International Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

public abstract class SplashAbilitySlice extends AbilitySlice
        implements SplashScreenCallback {
    private boolean isCancle = false;
    private static final int DELAY_TIME = 1000;

    @Override
    public final void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_splash);

        Database.get().getRandomWallpaper();

        EventHandler eventHandler = new EventHandler(EventRunner.create()) {
            @Override
            protected void processEvent(InnerEvent event) {
                if (!isCancle) {
                    Intent getIntent = new Intent();
                    Operation opt = new Intent
                            .OperationBuilder()
                            .withBundleName(getBundleName())
                            .withAbilityName(
                                    ((SplashScreenConfiguration) event.object)
                                            .getMainActivity().getName())
                            .build();
                    getIntent.setOperation(opt);
                    startAbility(getIntent);
                    terminate();
                }
            }
        };
        InnerEvent innerEvent = InnerEvent.get();
        innerEvent.object = onInit();
        eventHandler.sendEvent(innerEvent, DELAY_TIME);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        isCancle = false;
    }
}
